package com.wang.tool.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wang.tool.lock.core.LockBody;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Description
 * @Author shaopeng
 * @Date 2023/6/7
 * @Version 1.0
 */
class Demo {

    public static void main(String[] args) {
        HashMap<Long, Task> map = new HashMap<>();
        AtomicLong id = new AtomicLong(0);

        TaskManage manage = new TaskManage() {
            @Override
            public Task selectById(Long taskId) {
                return JSON.parseObject(JSON.toJSONString(map.get(taskId)), Task.class);
            }

            @Override
            public void doWithTrans(Runnable action) {
                action.run();
            }

            @Override
            protected Long insert(Task task) {
                Task value = JSON.parseObject(JSON.toJSONString(task), Task.class);
                map.put(id.incrementAndGet(), value);
                value.setId(id.get());
                return id.get();
            }

            @Override
            protected boolean updateStageOnNotComplete(TaskStage stage, int currentHandleTimes) {
                if (stage == null || stage.getId() == null) {
                    throw new IllegalArgumentException("任务不可为空");
                }
                Task task = map.get(stage.getId());
                if (task == null) {
                    return false;
                }
                if (task.getHandleTimes() != currentHandleTimes) {
                    return false;
                }
                task.setStatus(stage.getStatus());
                task.setBizStatus(stage.getBizStatus());
                task.setHandleTimes(task.getHandleTimes());
                task.setModel(JSON.parseObject(JSON.toJSONString(stage.getModel())));
                task.setCheckTime(stage.getCheckTime());
                task.setOutId(stage.getOutId());
                task.setGmtModified(new Date());
                return true;
            }

            @Override
            protected boolean updateFireOnComplete(Long taskId) {
                Task task = map.get(taskId);
                if (task == null) {
                    return false;
                }
                task.setFire(true);
                return true;
            }

            @Override
            protected boolean tryHandler(Long taskId) {
                Task task = map.get(taskId);
                if (task == null) {
                    return false;
                }
                if (task.getStatus() != TaskStatus.WAIT) {
                    return false;
                }
                task.setStatus(TaskStatus.RUNNING);
                return true;
            }

            @Override
            protected TaskHandler<?> findHandler(String handler) {
                if ("a".equals(handler)) {
                    return new TaskHandler() {
                        @Override
                        public String getName() {
                            return "a";
                        }

                        @Override
                        public LockBody generateBizLockBody(Task task) {
                            return null;
                        }

                        @Override
                        public TaskStage pre(Task task, Object param) {
                            System.out.println("a任务的参数" + param);

                            TaskBase baseBTask = TaskBase.build("b任务", "b");
                            //标记b任务的关联方是此任务
                            baseBTask.setRelateIds(Arrays.asList(task.getId()));
//                            发起b任务
                            Task bTask = create(baseBTask, 1);
//                            a任务中记录b任务id
                            JSONObject model = new JSONObject();
                            model.put("subTask", bTask.getId());
                            return task.toStage().nextTime(1, 1).model(model);
                        }

                        @Override
                        public TaskStage check(Task task) {
                            JSONObject model = task.modelTo(JSONObject.class);
                            Long bTaskId = model.getLong("subTask");
//                            查询b任务完成没
                            Task bTask = selectById(bTaskId);

//                             如果b完成了，自己也设为完成
                            return task.toStage().complete(bTask.judgeIsComplete()).nextTime(20, 0.7);
                        }
                    };
                } else if ("b".equals(handler)) {
                    return new TaskHandler() {
                        @Override
                        public String getName() {
                            return "b";
                        }

                        @Override
                        public LockBody generateBizLockBody(Task task) {
                            return null;
                        }

                        @Override
                        public TaskStage pre(Task task, Object param) {
                            System.out.println("b任务的参数" + param);
//                            异步发起任务
//
                            return task.toStage().nextTime(100, 0.5);
                        }

                        @Override
                        public TaskStage check(Task task) {
//                             模拟自检完成
                            return task.toStage().complete(true);
                        }
                    };
                }
                return null;
            }

            @Override
            protected void lockDo(LockBody body, Runnable action) {
//                LockServer server = null;
//                server.lockDo(body, () -> {
//                    action.run();
//                    return null;
//                });
                action.run();
            }

            @Override
            protected void onProcess(String method, Task task) throws Throwable {
                System.out.println("任务更新成功" + task.getId());
            }
        };


        TaskBase baseTask = TaskBase.build("a任务", "a");
        Task task = manage.create(baseTask, "123");
//        扫表 自检 触发b的完成，此时b完成，接着触发a的自检，a也完成了
        manage.check(2L);
//        结束


    }

}
